package com.happy_hao.msg.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.happy_hao.msg.exception.ServiceException;
import com.happy_hao.msg.mapper.EmailMapper;
import com.happy_hao.msg.po.Email;
import com.happy_hao.msg.util.EmailUtil;
import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

@Component
public class ScheduledTask {

    @Resource
    private EmailMapper emailMapper;

    @Resource
    private EmailUtil emailUtil;

    @Async
    @Scheduled(cron = "0 0/1 * * * ?")
    public void send(){
        List<Email> emailList = emailMapper.selectList(null);
        if(emailList !=null && !emailList.isEmpty()){
            Date now = new Date();
            for(Email email : emailList){
                if (email.getSendTime().before(now)){
                    try {
                        emailUtil.send(email);
                    } catch (MessagingException | UnsupportedEncodingException e) {
                        throw new ServiceException("策略发送邮件失败");
                    }
                    emailMapper.delete(new QueryWrapper<Email>().eq("email_id", email.getEmailId()));
                }
            }
        }else{
            System.out.println("邮件池为空");
        }
    }

}
